<template>
  <div class="page_report">
    <div  id="export_report_id" style="width: 1000px;margin: auto;">
      <div style="text-align: center;font-size: 20px;color: #1aabb8;margin-top: 50px;margin-bottom: 20px;">{{$t('common.trainerName')}}
        【{{ nickName }}】{{$t('common.autoReport')}} 
      </div>
      <div class="flex justify-end mb" >  
        <Button class="btnWhite" type="primary" style="margin-right:15px" @click="playVideo">{{$t('common.videoView')}}</Button>
         <Button  class="btnWhite" type="primary"  @click="doExport"  >{{$t('export')}} </Button></div>
      <Collapse v-model="collapseName" style="margin-bottom: 50px">

        <Panel name="baseInfo">
          {{$t('common.sportInfo')}} 
          <p slot="content">
            <Row class="form-row">
              <Col span="6" class="form_filed">{{$t('common.trainActionName')}}：</Col>
              <Col span="6" class="form_filed_val">{{ trainActionName }}</Col>
              <Col span="6" class="form_filed">{{$t('common.heft')}}：</Col>
              <Col span="6" class="form_filed_val">{{ weight}}kg</Col>
              <Col span="6" class="form_filed">{{$t('common.sportStartColumn')}}：</Col>
              <Col span="6" class="form_filed_val">{{ sportsRecord.startTrainTime }}</Col>
              <Col span="6" class="form_filed">{{$t('common.sportEndColumn')}} ：</Col>
              <Col span="6" class="form_filed_val">{{ sportsRecord.endTrainTime }}</Col>
            </Row>
          </p>
        </Panel>
        <Panel name="speed">
           {{$t('common.speedTarget')}} : {{ golaSpeed }} m/s
          <div slot="content">
              <div style="position: relative">
            <div style="text-align: center;padding: 10px;" >
             <span> {{$t('common.avgSpeed')}}:{{ groupStatistics.groupAvgSpeed }}m/s</span>&nbsp;&nbsp;&nbsp;&nbsp;
             <span> {{$t('common.maxSpeed')}} :{{ groupStatistics.groupMaxSpeed }}m/s</span>
            </div>
             <div
                style="
                  position: absolute;
                  right: 0;
                  top: 0;
                  cursor: pointer;
                  color: #2ac9cf;
                  font-weight: bold;
                "
                v-if="isSpeedBar"
                @click="changeViewLine"
              >
              {{$t('common.changeLine')}}  
              </div>
              <div
                v-else
                style="
                  position: absolute;
                  right: 0;
                  top: 0;
                  cursor: pointer;
                  color: #2ac9cf;
                  font-weight: bold;
                "
                @click="changeViewLine"
              >
                {{$t('common.changeBar')}}  
              </div>
            </div>
            <div ref="speed" style="height: 300px;"></div>

            <div style="margin: 0px 80px">
              <Table :columns="speedColumn" border :data="evaList" stripe>
                <template slot-scope="{ row, index }" slot="seq">
                  {{index + 1}}
                </template>
              </Table>
            </div>
          </div>

        </Panel>
        <Panel name="function">
          {{$t('common.power')}}   
          <div slot="content">
           <div style="position: relative">
            <div style="text-align: center;padding: 10px;" >
             <span> {{$t('common.avgPower')}}:{{ groupStatistics.groupAvgPower }}W</span>&nbsp;&nbsp;&nbsp;&nbsp;
             <span>{{$t('common.maxGoalPower')}}:{{ groupStatistics.groupMaxPower }}W</span>
            </div>
             <div
                style="
                  position: absolute;
                  right: 0;
                  top: 0;
                  cursor: pointer;
                  color: #2ac9cf;
                  font-weight: bold;
                "
                v-if="isPowerBar"
                @click="changeViewLineP"
              >
              {{$t('common.changeLine')}}  
              </div>
              <div
                v-else
                style="
                  position: absolute;
                  right: 0;
                  top: 0;
                  cursor: pointer;
                  color: #2ac9cf;
                  font-weight: bold;
                "
                @click="changeViewLineP"
              >
              {{$t('common.changeBar')}}  
              </div>
            </div>
            <div ref="function" style="height: 300px;"></div>

            <div style="margin: 0px 80px">
              <Table :columns="functionColumn" border :data="evaList" stripe>
                <template slot-scope="{ row, index }" slot="seq">
                  {{index + 1}}
                </template>
              </Table>
            </div>
          </div>
        </Panel>

        <Panel name="power">
          {{$t('common.workDone')}}   
          <div slot="content">
            <div style="position: relative">
            <div style="text-align: center;padding: 10px;" >
             <span>  {{$t('common.totalPower')}} :{{ groupStatistics.groupTotalStrength }}J</span>&nbsp;&nbsp;&nbsp;&nbsp;
             <span>{{$t('common.avaPower')}} :{{ groupStatistics.groupAvgStrength }}J</span>&nbsp;&nbsp;&nbsp;&nbsp;
             <span> {{$t('common.peakWork')}} :{{ groupStatistics.groupMaxStrength }}J</span>
            </div>
             <div
                style="
                  position: absolute;
                  right: 0;
                  top: 0;
                  cursor: pointer;
                  color: #2ac9cf;
                  font-weight: bold;
                "
                v-if="isWorkBar"
                @click="changeViewLineW"
              >
              {{$t('common.changeLine')}}  
              </div>
              <div
                v-else
                style="
                  position: absolute;
                  right: 0;
                  top: 0;
                  cursor: pointer;
                  color: #2ac9cf;
                  font-weight: bold;
                "
                @click="changeViewLineW"
              >
              {{$t('common.changeBar')}}  
              </div>
            </div>
            <div ref="strength" style="height: 300px;"></div>

            <div style="margin: 0px 80px">
              <Table :columns="strengthColumn" border :data="evaList" stripe>
                <template slot-scope="{ row, index }" slot="seq">
                  {{index + 1}}
                </template>
              </Table>
            </div>
          </div>
        </Panel>
      </Collapse>
    </div>
      <!-- 展示视频播放 -->
<Modal v-model="showVideoVisible" :mask-closable="false" width="800" :title="$t('common.videoView')" mask>
    <VideoModail :videoList="videoList" :curPlayId="curPlayId" :playVideoUrl="playVideoUrl"/>
    <div slot="footer" style="text-align: center">
        <Button @click="showVideoVisible=false">{{$t('cancel')}}</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import echarts from 'echarts'
import AnalysisReportApi from '@/api/analysisReportApi'
import html2canvas from 'html2canvas'
import { downloadByBase64 } from '../../utils/downloadImg'
import VideoApi from "@/api/videoApi";
import { getToken } from "@/libs/util";
import VideoModail from './videoModail.vue'
export default {
  name: 'page_report',
  components: {VideoModail},
  data () {
    return {
         isSpeedBar: true,
      isPowerBar: true,
      isWorkBar:true,
      showVideoVisible:false,
        videoList:[],
        curPlayId:'',
        playVideoUrl:'',
      nickName: '',
      weight: '',
      trainActionName: '',
      sportsRecordId: '',
      groupStatistics: {},
      sportsRecord: { startTrainTime: '', endTrainTime: '' },
      collapseName: ['baseInfo', 'speed', 'power', 'function'],
      speedDom: null,
      powerDom: null,
      functionDom: null,
      evaList: [],
      speedXaxis: [],
      avgSpeedDataArr: [], // 平均速度数组
      maxSpeedDataArr: [], // 最大速度数组
      golaSpeed: 0, // 目标速度
      color_no_pass: '#FE4C4C',
      avg_color: '#34DABA',
      max_color: '#0084F8',
      speedColumn: [
        { title: this.$t('common.frequency'), slot: 'seq' },
        { title:  this.$t('common.maxSpeed') + '(m/s)', key: 'maxSpeed' },
        { title: this.$t('common.avgSpeed') +  '(m/s)', key: 'avgSpeed' }
      ],
      // 功率
      avgFunctionDataArr: [],
      maxFunctionDataArr: [],
      functionColumn: [
        { title: this.$t('common.frequency'), slot: 'seq' },
        { title: this.$t('common.maxGoalPower') + '(W)', key: 'maxPower' },
        { title: this.$t('common.avgPower') + '(W)', key: 'avgPower' }
      ],
      strengthDataArr: [],
      strengthColumn: [
        { title: this.$t('common.frequency'), slot: 'seq' },
        { title: this.$t('common.workDone') + '(J)', key: 'strength' }
      ]
    }
  },
  mounted () {
    this.sportsRecordId = this.$route.query.sportsRecordId
    this.$Spin.show({
      render: (h) => {
        return h('div', [
          h('Icon', {
            'class': 'demo-spin-icon-load',
            props: {
              type: 'ios-loading',
              size: 18
            }
          }),
          h('div', 'Loading')
        ])
      }
    })
    this.initAnalysisData()
  },
  methods: {
    playVideo() {
       
       this.queryVideoList();
        
       },
       queryVideoList() {
       
       VideoApi.getVideoList(this.sportsRecordId).then(
         (res) => {
           
           this.videoList = res.data.data;
           if (this.videoList.length == 0) {
             
             this.$Message.error(this.$t('common.noVideoSport'));
             return;
           }
          
           const video = this.videoList[0];
           this.curPlayId = video.id;
           this.playVideoUrl= "web/video/play/" + video.id + "?token=" + getToken();
        
             setTimeout(()=>{
           this.showVideoVisible=true
          },1000)
           
         },
         (error) => {
           this.$Message.error(this.$t('common.noVideo') );
           this.videoList=[];
         }
       );
     },
    doExport () {
      // #export_report_id 就是我们要获取截图对应的 DOM 元素选择器
      html2canvas(document.querySelector('#export_report_id'), {
        useCORS: true, // 【重要】开启跨域配置
        scale: window.devicePixelRatio < 3 ? window.devicePixelRatio : 2,
        allowTaint: true // 允许跨域图片
      }).then((canvas) => {
        const imgData = canvas.toDataURL('image/jpeg', 1.0)
        downloadByBase64(imgData,  this.$t('common.reportExport') +  `-${new Date().getTime()}.png`)
      })
    },
     
        changeViewLine() {
      if (this.isSpeedBar) {
        this.initSpeedChartLine();
      } else {
        this.initSpeedChart();
      }
      this.isSpeedBar = !this.isSpeedBar;
    },
    changeViewLineP() {
      if (this.isPowerBar) {
        this.initFunctionChartLine()
      } else {
        this.initFunctionChart()
      }
      this.isPowerBar = !this.isPowerBar;
    },
 changeViewLineW() {
      if (this.isWorkBar) {
        this.initPowerChartLine();
      } else {
        this.initPowerChart();
      }
      this.isWorkBar = !this.isWorkBar;
    },
    initAnalysisData () {
      AnalysisReportApi.queryFreetrainAnalysisReport(this.sportsRecordId).then(res => {
        this.$Spin.hide()
        res = res.data.data
        this.nickName = res.nickName
        this.sportsRecord = res.sportsRecord
        this.weight = res.weight
        this.trainActionName = res.trainActionName
        this.evaList = res.eva
        this.groupStatistics = res.groupStatistics
        // 设置速度
        var speedAvgDataArr = []
        var speedMaxDataArr = []
        var functionAvgDataArr = []
        var functionMaxDataArr = []
        var strengthDataArr = []
        for (var i = 0; i < this.evaList.length; i++) {
          var eva = this.evaList[i]
          var color = this.avg_color
          var maxColor = this.max_color
          this.speedXaxis.push((i + 1) + '')
          speedAvgDataArr.push({
            name:  this.$t('common.avgSpeed') + '(m/s)', value: eva.avgSpeed, itemStyle: { 'color': color }
          })
          speedMaxDataArr.push({
            name: this.$t('common.maxSpeed') + '(m/s)', value: eva.maxSpeed, itemStyle: { 'color': maxColor }
          })
          functionAvgDataArr.push({
            name:  this.$t('common.avgPower') + '(W)', value: eva.avgPower, itemStyle: { 'color': this.avg_color }
          })
          functionMaxDataArr.push({
            name:   this.$t('common.maxGoalPower') +'(W)', value: eva.maxPower, itemStyle: { 'color': this.max_color }
          })
          strengthDataArr.push({
            name:  this.$t('common.workDone') +'(J)', value: eva.strength, itemStyle: { 'color': this.max_color }
          })
        }
        this.avgSpeedDataArr = speedAvgDataArr
        this.maxSpeedDataArr = speedMaxDataArr
        this.avgFunctionDataArr = functionAvgDataArr
        this.maxFunctionDataArr = functionMaxDataArr
        this.strengthDataArr = strengthDataArr
        this.initSpeedChart()
        this.initPowerChart()
        this.initFunctionChart()
      }, error => {
        this.$Message.error(error.response.data.msg)
        this.$Spin.hide()
      })
    },
    // 速度曲线
    initSpeedChart () {
      const option = {
        tooltip: {},
        legend: { 
          data: [ this.$t('common.avgSpeed'), this.$t('common.maxSpeed')]
        },
        grid: {
          show: false
        },
        xAxis: [
          {
            type: 'category',
            name:this.$t('common.frequency'),
            nameTextStyle: {
              color: '#aaa'
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            },
            splitLine: {
              show: false // 不显示网格线
            },
            data: this.speedXaxis
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: this.$t('common.speed') + '(m/s)',
            splitLine: {
              show: false // 不显示网格线
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            }
          }
        ],
        series: [
          {
            type: 'bar',
            color: '#34DABA',
            name: this.$t('common.avgSpeed'),
            data: this.avgSpeedDataArr
          },
          {
            type: 'bar',
            color: '#0084F8',
            name: this.$t('common.maxSpeed'),
            data: this.maxSpeedDataArr
          },
          {
            type: 'bar',
            name: this.$t('common.globalSpeed') + '(m/s)',
            data: [],
            markLine: {
              lineStyle: {
                type: 'dashed',
                color: '#aaa'
              },
              data: [
                {
                  name:  this.$t('common.globalSpeed'),
                  yAxis: this.golaSpeed
                }
              ]
            }
          }
        ]
      }
   if (this.speedDom) {
        this.speedDom.dispose();
      }
      this.speedDom = echarts.init(this.$refs.speed)
      this.speedDom.setOption(option)
    },
 initSpeedChartLine () {
      const option = {
        tooltip: {},
        legend: {
          data: [this.$t('common.avgSpeed'),this.$t('common.maxSpeed')]
        },
        grid: {
          show: false
        },
        xAxis: [
          {
            type: 'category',
            name:this.$t('common.frequency'),
            nameTextStyle: {
              color: '#aaa'
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            },
            splitLine: {
              show: false // 不显示网格线
            },
            data: this.speedXaxis
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: this.$t('common.speed') + '(m/s)',
            splitLine: {
              show: false // 不显示网格线
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            }
          }
        ],
        series: [
          {
            type: 'line',
            color: '#34DABA',
            name: this.$t('common.avgSpeed'),
            data: this.avgSpeedDataArr
          },
          {
            type: 'line',
            color: '#0084F8',
            name: this.$t('common.maxSpeed'),
            data: this.maxSpeedDataArr
          },
          {
            type: 'line',
            name:  this.$t('common.globalSpeed') + '(m/s)',
            data: [],
            markLine: {
              lineStyle: {
                type: 'dashed',
                color: '#aaa'
              },
              data: [
                {
                  name:  this.$t('common.globalSpeed'),
                  yAxis: this.golaSpeed
                }
              ]
            }
          }
        ]
      }
   if (this.speedDom) {
        this.speedDom.dispose();
      }
      this.speedDom = echarts.init(this.$refs.speed)
      this.speedDom.setOption(option)
    },
    // 功率
    initFunctionChart () {
      const option = {
        tooltip: {},
        legend: {
          data: [this.$t('common.avgPower'), this.$t('common.maxGoalPower')]
        },
        grid: {
          show: false
        },
        xAxis: [
          {
            type: 'category',
            name: this.$t('common.frequency'),
            nameTextStyle: {
              color: '#aaa'
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            },
            splitLine: {
              show: false // 不显示网格线
            },
            data: this.speedXaxis
          }
        ],
        yAxis: [
          {
            type: 'value',
            name:  this.$t('common.power') + '(W)',
            splitLine: {
              show: false // 不显示网格线
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            }
          }
        ],
        series: [
          {
            type: 'bar',
            color: '#34DABA',
            name: this.$t('common.avgPower'),
            data: this.avgFunctionDataArr
          },
          {
            type: 'bar',
            color: '#0084F8',
            name: this.$t('common.maxGoalPower'),
            data: this.maxFunctionDataArr
          }
        ]
      }
         if (this.functionDom) {
        this.functionDom.dispose();
      }
      this.functionDom = echarts.init(this.$refs.function)
      this.functionDom.setOption(option)
    },
initFunctionChartLine () {
      const option = {
        tooltip: {},
        legend: {
          data: [this.$t('common.avgPower'), this.$t('common.maxGoalPower')]
        },
        grid: {
          show: false
        },
        xAxis: [
          {
            type: 'category',
            name: this.$t('common.frequency'),
            nameTextStyle: {
              color: '#aaa'
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            },
            splitLine: {
              show: false // 不显示网格线
            },
            data: this.speedXaxis
          }
        ],
        yAxis: [
          {
            type: 'value',
            name:  this.$t('common.power') + '(W)',
            splitLine: {
              show: false // 不显示网格线
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            }
          }
        ],
        series: [
          {
            type: 'line',
            color: '#34DABA',
            name: this.$t('common.avgPower'),
            data: this.avgFunctionDataArr
          },
          {
            type: 'line',
            color: '#0084F8',
            name: this.$t('common.maxGoalPower'),
            data: this.maxFunctionDataArr
          }
        ]
      }
         if (this.functionDom) {
        this.functionDom.dispose();
      }
      this.functionDom = echarts.init(this.$refs.function)
      this.functionDom.setOption(option)
    },
    // 功
    initPowerChart () {
      const option = {
        tooltip: {},
        legend: {
          data: [this.$t('common.workDone')]
        },
        grid: {
          show: false
        },
        xAxis: [
          {
            type: 'category',
            name: this.$t('common.frequency'),
            nameTextStyle: {
              color: '#aaa'
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            },
            splitLine: {
              show: false // 不显示网格线
            },
            data: this.speedXaxis
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: this.$t('common.workDone') + '(J)',
            splitLine: {
              show: false // 不显示网格线
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            }
          }
        ],
        series: [
          {
            type: 'bar',
            color: this.max_color,
            name: this.$t('common.workDone'),
            data: this.strengthDataArr
          }
        ]
      }
        if (this.powerDom) {
        this.powerDom.dispose();
      }
      this.powerDom = echarts.init(this.$refs.strength)
      this.powerDom.setOption(option)
    },
    initPowerChartLine () {
      const option = {
        tooltip: {},
        legend: {
          data: [this.$t('common.workDone')]
        },
        grid: {
          show: false
        },
        xAxis: [
          {
            type: 'category',
            name: this.$t('common.frequency'),
            nameTextStyle: {
              color: '#aaa'
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            },
            splitLine: {
              show: false // 不显示网格线
            },
            data: this.speedXaxis
          }
        ],
        yAxis: [
          {
            type: 'value',
            name:  this.$t('common.workDone') + '(J)',
            splitLine: {
              show: false // 不显示网格线
            },
            axisLine: {
              lineStyle: {
                color: '#aaa'
              }
            }
          }
        ],
        series: [
          {
            type: 'line',
            color: this.max_color,
            name:  this.$t('common.workDone'),
            data: this.strengthDataArr
          }
        ]
      }
        if (this.powerDom) {
        this.powerDom.dispose();
      }
      this.powerDom = echarts.init(this.$refs.strength)
      this.powerDom.setOption(option)
    }

  }
}
</script>
<style>
  html, body {
    overflow: auto;
    overflow-x: hidden;
    overflow-y: auto;
  }

  .demo-spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
  }
</style>
